﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using cecbClasses.Data_Adapters.Project;
using cecbData;
using System.Runtime.Remoting.Messaging;

namespace CECB
{
    /// <summary>
    /// Interaction logic for TemplateViwer_Window.xaml.xaml
    /// </summary>
    public partial class TemplateViwer_Window : Window
    {
        private Func_Projects _ObjProjcts;

        private DSSEntities _dataContext;
        private String _selectedImpactCat = "";

        private TreeViewItem _selectedImpactTreeViewItem = null;

        public TemplateViwer_Window()
        {
            InitializeComponent();

            _dataContext = new DSSEntities();

            var quary = from c in _dataContext.Projects
                        where !_dataContext.ProjectActivities.Any(p => p.proj_reference == c.proj_reference)
                            && !_dataContext.ProjectImpacts.Any(q => q.proj_reference == c.proj_reference)
                        select c;


            ProjectAutocompleteTextBox.ItemsSource = quary;
            _ObjProjcts = new Func_Projects();
            List<Categories> CatgryList = _ObjProjcts.GetAllCatogries();
            comboBox_projCatogory.ItemsSource = CatgryList;

            List<cecbData.ProjectTypes> ProjectTypeList = _ObjProjcts.GetAllProjectTypes();
            comboBox_projType.ItemsSource = ProjectTypeList;

        }


        public TemplateViwer_Window(String projCategory, String projType)
        {

            InitializeComponent();

            _dataContext = new DSSEntities();
            var quary = from c in _dataContext.Projects
                        where !_dataContext.ProjectActivities.Any(p => p.proj_reference == c.proj_reference)
                            && !_dataContext.ProjectImpacts.Any(q => q.proj_reference == c.proj_reference)
                        select c;


            ProjectAutocompleteTextBox.ItemsSource = quary;
            _ObjProjcts = new Func_Projects();

            comboBox_projCatogory.Text = projCategory;
            comboBox_projType.Text = projType;

            try
            {
                treeViewImpacts.Items.Clear();
                treeViewActivities.Items.Clear();


                fillImpacts(projCategory, projType);

            }

            catch (NullReferenceException)
            {
                MessageBox.Show("No values in that category !", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                this.Close();
            }

        }




        private bool _isProjectSelected = false;
        private String _selectedProject = "";
        private void ProjectAutocomplete_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((AutoCompleteBox)sender).SelectedItem == null)
            {

                _isProjectSelected = false;
            }
            else
            {
                _isProjectSelected = true;
                _selectedProject = ((Projects)(((AutoCompleteBox)sender).SelectedItem)).proj_reference.ToString();

            }
        }

         

        private void comboBox_projCatogory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            treeViewImpacts.Items.Clear();
            treeViewActivities.Items.Clear();
        }

         

        private void filltemplate(String ref1, String ref2)
        {


            comboBox_projCatogory.Text = "National";
            comboBox_projType.Text = "Railway";
            comboBox_projCatogory.IsEnabled = false;
            comboBox_projType.IsEnabled = false;

            treeViewImpacts.Items.Clear();
            treeViewActivities.Items.Clear();
            String projCategoryReference = ref1;
            String projectTypeRef = ref2;
            List<Templates> impactRef;


            IQueryable<Templates> query = from c in _dataContext.Templates
                                          where c.proj_catref.Equals(projCategoryReference)
                                          &&
                                          c.proj_typeref.Equals(projectTypeRef)
                                          select c;

            impactRef = query.ToList();
            fillImpacts(projCategoryReference, projectTypeRef);

        }



        private void comboBox_projType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBox_projType.SelectedIndex > -1)
            {
                try
                {
                    treeViewImpacts.Items.Clear();
                    treeViewActivities.Items.Clear();
                    String projCategoryReference = comboBox_projCatogory.SelectedValue.ToString();
                    String projectTypeRef = comboBox_projType.SelectedValue.ToString();

                    fillImpacts(projCategoryReference, projectTypeRef);

                }
                catch (NullReferenceException)
                {
                    MessageBox.Show("No values in that category !", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                    this.Close();
                }

            }
            else
            {
                MessageBox.Show("Select a project category!", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        public void fillImpacts(String catref, String actref)
        {

            IQueryable<Components> qComponents = (from c in _dataContext.Components

                                                  select c).Distinct();

            int nodeCount = 0;
            foreach (Components com in qComponents)
            {

                treeViewImpacts.Items.Add(new TreeViewItem()
                {
                    Header = com.cmpt_name

                });

                List<Get_Template_Impacts_Result> tempImpactsList = new cecbClasses.Data_Adapters.Template.Template().GetTemplateImpactsValues("");


                foreach (Get_Template_Impacts_Result imp in tempImpactsList)
                {

                    if (com.cmpt_name == imp.cmpt_name)
                    {
                        ((TreeViewItem)treeViewImpacts.Items[nodeCount]).Items.Add(SetTreeViewImpacts(imp.impt_name.ToString(), imp.percentage.ToString(), imp.impt_reference.ToString()));
                        ((TreeViewItem)treeViewImpacts.Items[nodeCount]).IsExpanded = true;
                    }
                }

                nodeCount++;

            }

            List<String> qAct = (from c in _dataContext.Activities
                                 select c.actv_phase).Distinct().ToList();
            int count = 0;
            foreach (String act in qAct)
            {

                treeViewActivities.Items.Add(new TreeViewItem()
                {
                    Header = act

                });

                List<Get_Template_ActivitiesWithReference_Result> activityWithReferenceList = new cecbClasses.Data_Adapters.Template.Template().GetTemplateActivityValuesWithReference("");


                foreach (Get_Template_ActivitiesWithReference_Result acti in activityWithReferenceList)
                {
                    if (acti.actv_phase.Equals(act))
                    {
                        ((TreeViewItem)treeViewActivities.Items[count]).Items.Add(SetTreeViewImpacts(acti.actv_name.ToString(), acti.percentage.ToString(), acti.actv_reference.ToString()));
                        ((TreeViewItem)treeViewActivities.Items[count]).IsExpanded = true;
                    }
                }
                count++;

            }



        }


        private TreeViewItem SetTreeViewImpacts(string text, String val, String displyVal)
        {
            TreeViewItem item = new TreeViewItem();

            item.IsExpanded = true;

            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;

            CheckBox chb = new CheckBox();
            chb.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            chb.IsChecked = true;
            Label lbl = new Label();
            lbl.Name = "lblImpText";
            lbl.Content = text;
            Label lblval = new Label();
            lblval.Content = " : " + val + "%";
            lblval.Foreground = Brushes.Red;
            lblval.FontSize = 14;
            stack.Children.Add(chb);
            stack.Children.Add(lbl);
            stack.Children.Add(lblval);

            item.Header = stack;

            item.Foreground = Brushes.Brown;
            item.BorderBrush = Brushes.Black;
            item.FontStyle = FontStyles.Italic;
            item.Cursor = Cursors.Hand;
            item.FontSize = 13;
            item.Height = 22;
            item.DisplayMemberPath = displyVal;


            return item;
        }


        private TreeViewItem SetTreeViewActivity(string text, String displyVal)
        {


            TreeViewItem item = new TreeViewItem();
            CheckBox chb = new CheckBox();
            chb.Height = 12;
            chb.Width = 12;
            item.IsExpanded = true;

            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;


            Label lbl = new Label();
            lbl.Name = "lblImpText";
            lbl.Content = text;
            lbl.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            stack.Children.Add(chb);
            stack.Children.Add(lbl);


            item.Header = stack;

            item.Foreground = Brushes.Brown;
            item.BorderBrush = Brushes.Black;
            item.FontStyle = FontStyles.Italic;
            item.Cursor = Cursors.Hand;
            item.FontSize = 13;
            item.Height = 22;
            item.DisplayMemberPath = displyVal;


            return item;
        }

        private void comboBox_projType_DropDownOpened_1(object sender, EventArgs e)
        {
            if (comboBox_projCatogory.SelectedIndex < 0)
            {
                MessageBox.Show("Select a category", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                comboBox_projType.SelectedIndex = -1;
            }
        }



        private int _selectedItemCount = 0;
        void GetSelectedItems(TreeView trv)
        {
            List<TreeViewItem> deletList = new List<TreeViewItem>();

            foreach (TreeViewItem it in trv.Items)
            {
                foreach (TreeViewItem cit in it.Items)
                {
                    if ((bool)(((cit as TreeViewItem).Header as StackPanel).Children.OfType<CheckBox>().First()).IsChecked)
                    {

                        deletList.Add(cit);

                    }

                }

            }

            foreach (TreeViewItem dtv in deletList)
            {

                foreach (TreeViewItem x in trv.Items)
                {

                    x.Items.Remove(dtv);
                }
            }
            trv.Items.Refresh();
            _selectedItemCount += deletList.Count;
        }



        private void treeViewActivities_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            TreeViewItem tvi = (TreeViewItem)treeViewActivities.SelectedItem;
            if (tvi != null)
            {
                _selectedImpactCat = tvi.Header.ToString();
                _selectedImpactTreeViewItem = tvi;
                if ((bool)(((tvi as TreeViewItem).Header as StackPanel).Children.OfType<CheckBox>().First()).IsChecked)
                {

                    tvi.Background = Brushes.Red;
                }

            }
        }

        AsyncCallback callback;
        SaveTemplateDataDelegate del;
        public delegate void SaveTemplateDataDelegate();
        AsyncResult result;
        public void OnCompletionSaveTemplateData(IAsyncResult res)
        {

            result = (AsyncResult)res;
            SaveTemplateDataDelegate initialDel = (SaveTemplateDataDelegate)result.AsyncDelegate;

            if (result.EndInvokeCalled == false)
            {
                return;
            }

        }


        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (_isProjectSelected)
            {
                if (treeViewActivities.HasItems && treeViewImpacts.HasItems)
                {
                    if (MessageBox.Show("You are about to save the template for ' " + ProjectAutocompleteTextBox.Text + "' project. Confirm to continue?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {


                        this.Cursor = Cursors.Wait;
                        saveTemplateData();
                        this.Cursor = Cursors.Hand;
                        MessageBox.Show("Template saved successfully!", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                        this.Close();
                    }
                     
                }
                else
                {
                    MessageBox.Show("Select a template befor continue!", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
                MessageBox.Show("Select a project to apply the template!", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void saveTemplateData()
        {
            insertImpactsAndActivities(treeViewActivities, _selectedProject, 1);
            insertImpactsAndActivities(treeViewImpacts, _selectedProject, 2);


        }


        private bool insertImpactsAndActivities(TreeView trv, String projId, int type)
        {


            try
            {
                foreach (TreeViewItem it in trv.Items)
                {
                    foreach (TreeViewItem cit in it.Items)
                    {

                        if ((bool)(((cit as TreeViewItem).Header as StackPanel).Children.OfType<CheckBox>().First()).IsChecked)
                        {
                            if (type == 1)
                                new cecbClasses.Data_Adapters.ImpactAndActivity.Func_Activities().insertProjectActivities(projId, cit.DisplayMemberPath.ToString());
                            else
                                new cecbClasses.Data_Adapters.ImpactAndActivity.Func_Impacts().insertProjectImpacts(projId, cit.DisplayMemberPath.ToString());
                        }
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private void ImpactsAutocompleteTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {

            e.Handled = true;

        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }


    }
}
